<template>
  <div>
    <BasicTable @register="registerTable">
      <template #toolbar>
        <a-button
          type="primary"
          v-if="hasPermission(['sysForm:add'])"
          @click="handleCreate"
        >
          新增
        </a-button>
      </template>

      <template #action="{ record }">
        <TableAction
          :actions="[
            {
              auth: 'sysForm:edit',
              label: '编辑',
              onClick: handleEdit.bind(null, record),
            },
            {
              auth: 'sysForm:delete',
              color: 'error',
              label: '删除',
              popConfirm: {
                title: '是否确认删除',
                confirm: handleDelete.bind(null, record),
              },
            },
          ]"
        />
      </template>
    </BasicTable>
    <EditModal @register="registerModal" @success="handleSuccess" />
  </div>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
export default defineComponent({
  name: 'SysForm',
});
</script>
<script lang="ts" setup>
import { usePermission } from '@/hooks/web/usePermission';
import { BasicTable, useTable, TableAction } from '@/components/Table';
import { page, del } from '@/api/dev/sysFormManage';
import { useModal } from '@/components/Modal';
import EditModal from './EditModal.vue';
import { useMessage } from '@/hooks/web/useMessage';
import { columns, searchFormSchema } from './data';
const { createMessage } = useMessage();
const [registerModal, { openModal }] = useModal();
const { hasPermission } = usePermission();
const [
  registerTable,
  { reload, getRowSelection, clearSelectedRowKeys, setSelectedRowKeys },
] = useTable({
  title: '列表',
  api: page,
  columns,
  formConfig: {
    labelWidth: 120,
    schemas: searchFormSchema,
    baseColProps: { span: 12 },
  },
  rowSelection: {
    type: 'radio',
  },
  useSearchForm: true,
  showTableSetting: true,
  bordered: true,
  showIndexColumn: false,
  actionColumn: {
    width: 120,
    title: '操作',
    dataIndex: 'action',
    slots: { customRender: 'action' },
    fixed: 'right',
  },
});
function handleCreate() {
  openModal(true, {
    isUpdate: false,
  });
}
function handleEdit(record: Recordable) {
  openModal(true, {
    record,
    isUpdate: true,
  });
}
function handleDelete(record: Recordable) {
  del([record.id]).then(() => {
    createMessage.success(`删除成功`);
    reload();
  });
}
function handleSuccess() {
  reload();
}

defineExpose({
  getData() {
    const { selectedRowKeys } = getRowSelection();
    const keys = selectedRowKeys as string[];
    if (keys && !keys.length) {
      createMessage.error('请选择表单');
      return;
    }
    return keys[0];
  },
  clearSelectedRowKeys,
  setSelectedRowKeys,
});
</script>
